package biz

import (
	"t11Lib/t11Errors"
	"t11Lib/t11Model"
	"亚太-iot-服务器/models"
)

type gatewayBiz struct{}

var GatewayBiz gatewayBiz

func (self gatewayBiz) ResetAndRegister(conn *t11Model.DbConn, gwId string, wxToken *models.JwtToken) t11Errors.T11Error {
	//重置网关
	if e := self.Reset(conn, gwId); e != nil {
		return e
	}
	//gwId已经在controller中检查过了
	_, e := models.GatewayDao.CreateOrUpdateGateway(conn, gwId, wxToken)
	return e
}

func (self gatewayBiz) Reset(conn *t11Model.DbConn, gwId string) t11Errors.T11Error {

	//重置网关
	return t11Model.Transacrtion(conn, func() t11Errors.T11Error {

		//列出设备列表
		var devIds []string
		devs, err := models.DeviceDao.GetByGwIds(conn, []string{gwId})
		if err != nil {
			return err
		}

		if len(devs) > 0 {

			for _, dev := range devs {
				devIds = append(devIds, dev.Id)
			}

			// 删除device log
			if e := models.DeviceLogDao.DeleteByDevId(conn, devIds); e != nil {
				return e
			}
			// 删除device kv
			if e := models.DeviceKvDao.DeleteByDevId(conn, devIds); e != nil {
				return e
			}
			// 删除device
			if e := models.DeviceDao.DeleteByGwId(conn, gwId); e != nil {
				return e
			}
			// 删除user device
			if e := models.UserDeviceDao.DeleteByDevId(conn, devIds); e != nil {
				return e
			}
			// 删除user device kv
			if e := models.UserKvDao.DeleteDeviceKvByDevId(conn, devIds); e != nil {
				return e
			}
		}

		// 删除user gateway kv
		if e := models.UserKvDao.DeleteGatewayKvByGwId(conn, gwId); e != nil {
			return e
		}

		return models.GatewayDao.SetGatewayUser(conn, gwId, "")
	})
}

func (self gatewayBiz) GetList(conn *t11Model.DbConn, tk *models.JwtToken) ([]*models.Gateway, t11Errors.T11Error) {
	return models.GatewayDao.GetGatewaysByUser(conn, tk)
}

func (self gatewayBiz) GetUserGatewayKvs(conn *t11Model.DbConn, tk *models.JwtToken) ([]*models.UserGatewayKv, t11Errors.T11Error) {
	return models.UserKvDao.GetGatewayKvByUser(conn, tk)
}

func (self gatewayBiz) ListDevices(conn *t11Model.DbConn, userId string) ([]*models.Device, t11Errors.T11Error) {
	return models.DeviceDao.GetByUser(conn, userId)
}

func (self gatewayBiz) GetById(conn *t11Model.DbConn, gwId string) (*models.Gateway, t11Errors.T11Error) {
	return models.GatewayDao.GetById(conn, gwId)
}
